"use client";

import { ConfigOption } from "@/src/types/types";
import { ChevronDownIcon } from "@chakra-ui/icons";
import { Button, Menu, MenuButton, MenuItem, MenuList } from "@chakra-ui/react";
import { useEffect, useMemo, useState } from "react";

export type SelectMenuOption = {
  name: string;
  value: number;
};

function SelectMenu({
  select = 0,
  options,
  onChange,
}: {
  select?: number;
  options: SelectMenuOption[];
  onChange?: (index: number) => void;
}) {
  const [currentSelect, setCurrentSelect] = useState(0);
  const currentSelectOption = useMemo(() => {
    return options[currentSelect] || "";
  }, [currentSelect, options]);

  useEffect(() => {
    setCurrentSelect(select);
  }, [select]);

  const changeSelect = (index: number) => {
    setCurrentSelect(index);
    onChange && onChange(index);
  };

  return (
    <Menu>
      <MenuButton
        as={Button}
        rightIcon={<ChevronDownIcon fill={"#fff"} boxSize={"6"} />}
        w={"100%"}
        textAlign={"left"}
        className="selecet-menu-btn !rounded"
        sx={{ backgroundColor: "rgb(65,107,61)" }}
      >
        {currentSelectOption && typeof currentSelectOption === "object"
          ? currentSelectOption.name
          : ""}
      </MenuButton>
      <MenuList
        padding={0}
        overflow={"hidden"}
        zIndex={10}
        className="!bg-gray-900 border border-gray-700 rounded-md"
      >
        {options.map((option, index) => (
          <MenuItem
            key={index}
            className="select-menu-item"
            onClick={() => changeSelect(index)}
          >
            {option.name}
          </MenuItem>
        ))}
      </MenuList>
    </Menu>
  );
}

export default SelectMenu;
